package org.sky.sys.util.multipledatabase.factory;

import org.apache.logging.log4j.Logger;
import org.sky.sys.entity.SysDatasource;
import org.sky.sys.mapper.SysDatasourceMapper;
import org.sky.sys.util.BspUtils;
import org.sky.sys.util.multipledatabase.connect.DBConnectionPool;
import org.sky.util.LogUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author weifx
 * @Title: MultipleConnectFactory
 * @ProjectName springboot-platform
 * @Description: TODO{多数据源连接池工厂类}
 * @date 2019/4/16 12:12
 * @Version 1.0
 */
public class MultipleConnectFactory {
    private final static Logger log = LogUtils.getLogger(MultipleConnectFactory.class);
    /**
     * 存放连接池容器
     */
    private static Map<String, DBConnectionPool> multipleConnectFactory = new HashMap();

    /**
     * 构造方法私有化
     */
    private MultipleConnectFactory(){
    }
    /**
     * 获取数据库连接池
     * @param databaseCode
     * @return
     */
    public static synchronized DBConnectionPool getDBConnectionPool(String databaseCode){
        DBConnectionPool pool = multipleConnectFactory.get(databaseCode);
        if(null == pool){
            log.info("数据源连接池{}未创建,开始创建数据源连接池... ...",databaseCode);
            SysDatasourceMapper sysDatasourceMapper = BspUtils.getBean(SysDatasourceMapper.class);
            Example example = new Example(SysDatasource.class);
            example.createCriteria().andEqualTo("code",databaseCode);
            SysDatasource sysDatasource = sysDatasourceMapper.selectOneByExample(example);
            Properties databseProperties = new Properties();
            databseProperties.put("type",sysDatasource.getType());
            databseProperties.put("driver-class-name",sysDatasource.getDriverClassName());
            databseProperties.put("url",sysDatasource.getUrl());
            databseProperties.put("username",sysDatasource.getUsername());
            databseProperties.put("password",sysDatasource.getPassword());
            pool = new DBConnectionPool(databseProperties);
            multipleConnectFactory.put(databaseCode,pool);
        }else{
            log.info("数据源连接池{}已经存在,返回已存在数据源连接池... ...",databaseCode);
        }
        return pool;
    }
}
